﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DAL.Interfaces;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using DAL.Models;

namespace DAL.Infrastructure
{
    public abstract class RepositoryBase<TEntity> : IRepository<TEntity> where TEntity : class, IEntity
    {
        private IContext _context;

        public RepositoryBase(IContext repositoryContext)
        {
            _context = repositoryContext ?? new ApplicationContext();
        }

        private IDbSet<TEntity> DbSet
        {
            get
            {
                return _context.Set<TEntity>();
            }
        }

        public TEntity Find(object[] keys)
        {
            TEntity entity = ((DbSet<TEntity>)DbSet).Find(keys);
            if (entity!=null){
                ((DbSet<TEntity>)DbSet).Attach(entity);
            }
            return entity;
        }
        public IQueryable<TEntity> GetAllValidados()
        {
            return ((DbSet<TEntity>)DbSet).AsQueryable<TEntity>();
        }
        public List<TEntity> GetAll()
        {
            return ((DbSet<TEntity>)DbSet).ToList<TEntity>();           
        }
        public void Remove(TEntity entity)
        {
            DbSet.Remove(entity);
            _context.SaveChanges();
        }
        public void Edit(TEntity entity)
        {
            TEntity[] arrayEntities = {entity};
            _context.Set<TEntity>().AddOrUpdate<TEntity>(arrayEntities);
            _context.SaveChanges();
        }
        public void Add(TEntity entity)
        {
            DbSet.Add(entity);
            _context.SaveChanges();
        }
        

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (_context != null)
                {
                    _context.Dispose();
                    _context = null;
                }
            }
        }
    } 
}
